package com.lin.config.threadpool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class ThreadPoolBeanConfig extends AsyncConfigurerSupport {
    public static final String DEFAULT_POOL = "defaultThreadPoolExecutor";
    public static final String DEFAULT_POOL_PREFIX = "Async-Customer-";

    @Bean(DEFAULT_POOL)
    public Executor defaultThreadPoolExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数数量
        threadPoolTaskExecutor.setCorePoolSize(9);
        //最大运行线程数量
        threadPoolTaskExecutor.setMaxPoolSize(90);
        //队列数量,如果超过队列则丢弃任务，并抛出异常
        threadPoolTaskExecutor.setQueueCapacity(1000);
        threadPoolTaskExecutor.setThreadNamePrefix(DEFAULT_POOL_PREFIX);
        threadPoolTaskExecutor.setTaskDecorator(new TraceLogMdcTaskDecorator());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return defaultThreadPoolExecutor();
    }
}
